// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

var UnitTools = require('UnitTools')
var CreatorHelper = require('CreatorHelper')
var UnitTools = require('UnitTools')
var Config = require('Config')
var ClickManager = require('ClickManager')
var NetworkManager = require('NetworkManager')
var AudioManager = require('AudioManager')

var tableItem = cc.Class({
    name: 'tableItem',
    properties: {
        tableId: 0,
        config1: '',
        config2: '',
        current: '',
        statusText: ''
    }
})

cc.Class({
    extends: cc.Component,

    properties: {
        moreBtn: cc.Node,   // 更多联盟按钮
        moreBox: cc.Node,   // 更多联盟框

        token: null,
        contentScroll: cc.ScrollView,   // 滚动内容区域
        contentNode: cc.Node,   // 滚动内容节点

        tableItems: {
            type: tableItem,
            default: []
        },
        tableItemPrefab: cc.Prefab,
        createTablePrefab: cc.Prefab,
        modelCreateTable: cc.Node,      // 创建牌桌node

        createTableOneStatus: false,
        tableLength: 0
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        CreatorHelper.loadPrefab('prefabs/Bgm', (node) => {
            this.node.addChild(node)
            node.getComponent('Bgm')._play()
        })

        this.token = cc.sys.localStorage.getItem('__TOKEN__')

        ClickManager.onClick(this.moreBtn, this, () => {
            this.showAndHide()
        })

        let rid = ClickManager.ccGetCache('__RID__')
        this.getTableInfo(rid)
        this.dynameicUpdateDate()
    },

    start () {
    },

    onEnable () {
        NetworkManager.updateUserInfo()
    },

    // 动态获取桌子数据
    dynameicUpdateDate () {
        cc.director.getScheduler().schedule(() => {
            this.getTableInfo(ClickManager.ccGetCache('__RID__'))
        }, this, 1)
    },

    // 获取桌子信息
    getTableInfo (rid) {
        NetworkManager.onConnectedToHall( (hallService) => {
            hallService.proxy.switchTheUnion(this.token, rid, (data) => {
                if (data.ok && data.code === 200) {
                    ClickManager.ccSetCache('__RID__', data.rid)
                    let list = JSON.parse(data.list)
                    this.drawNodeList(list)
                    if (data.name !== null) {
                        var uname = cc.find('Canvas/bg/name')
                        uname.getComponent(cc.Label).string = '当前联盟: ' + data.name
                    }
                }
            })
        })
    },

    // 渲染节点
    drawNodeList (list) {
        this.createTableToOne()

        var length = list.length
        if (this.contentNode.childrenCount == null) {
            var nodeLength = 0
        } else {
            var nodeLength = this.contentNode.childrenCount - 1
        }

        if (length > nodeLength) {
            for (let i = 0; i < length - nodeLength; i++) {
                let item = cc.instantiate(this.tableItemPrefab)
                let obj = {
                    tableId: list[i].id,
                    config1: `人数：${list[i].number}，局数：${list[i].innings}`,
                    config2: `低注：${list[i].low_grade}，最低余额：${list[i].min_balance}`,
                    current: `当前：${list[i].curNumber}人，${list[i].curInnings}局，房间ID：${list[i].id} `,
                    statusText: list[i].gameing ? `游戏中` : `等待中`
                }

                this.contentNode.addChild(item)
                item.getComponent('TableItemList').init(obj)
            }
            this.tableLength = length
        } else if (length < nodeLength) {
            var childNode = this.contentNode.children
            for (let i = 0; i < childNode.length; i++) {
                var hasTid = false
                for (let j = 0; j < length; j++) {
                    if (childNode[i].tid == list[j].id) {
                        hasTid = true
                        break ;
                    }
                }
                if (!hasTid && !UnitTools.isNullOrUndefined(childNode[i].tid)) {
                    this.contentNode.removeChild(childNode[i])
                }
            }
            this.tableLength = length
        }
    },

    // 移除全部桌子并重新渲染
    removeAllTableAndDraw () {
        this.contentNode.removeAllChildren()
        this.createTableOneStatus = false
        this.getTableInfo(ClickManager.ccGetCache('__RID__'))
    },

    // 创建创建桌子的桌子
    createTableToOne () {
        if (!this.createTableOneStatus) {
            let createTablePrefab = cc.instantiate(this.createTablePrefab)
            this.contentNode.addChild(createTablePrefab)
            this.createTableOneStatus = true

            ClickManager.onClick(createTablePrefab, createTablePrefab, () => {
                this.modelCreateTable.active = true
            })
        }
    },

    // 点击显示和隐藏
    showAndHide () {
        this.moreBox.active = !this.moreBox.active
    },
});
